<template>
  <!-- <div class="content-box">
  <common-header :title="title"></common-header>-->
  <div class="page-content">
    <van-field
      v-model="userName"
      required
      clearable
      label="账号"
      placeholder="请设置6-10位数字、英文组成的用户名!"
      :error-message="userNameMessage"
    />
    <!-- <van-field
      v-model="phoneNum"
      clearable
      type="number"
      label="手机号"
      placeholder="请输入手机号"
      required
      :error-message="phoneNumMessage"
    /> -->
    <van-field
      v-if="!msmShow"
      ref="sms"
      v-model="sms"
      center
      required
      clearable
      label="验证码"
      placeholder="请输入验证码"
      :error-message="smsErrMessage"
    >
      <img
        slot="button"
        class="code"
        @click="getCode"
        :src="codeUrl"
        style="border: 1px solid #ccc; float: right;"
        title="点击换一张"
      />
      <!-- <van-button
        slot="button"
        size="small"
        :type="smsType"
        :disabled="smsDisabled"
        @click="sendSms"
      >{{smsMessage}}</van-button>-->
    </van-field>
    <van-field
      v-else
      ref="sms"
      v-model="sms"
      center
      required
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
      :error-message="smsErrMessage"
      @focus="isSended"
    >
      <van-button
        slot="button"
        size="small"
        :type="smsType"
        :disabled="smsDisabled"
        @click="sendSms"
      >{{smsMessage}}</van-button>
    </van-field>
    <van-field
      v-model="password"
      clearable
      type="password"
      label="登录密码"
      placeholder="请设置6-14位数字、英文组成的登录密码!"
      required
      :error-message="passwordMessage"
    />
    <van-field
      v-model="payPassword"
      clearable
      type="password"
      label="支付密码"
      placeholder="请设置6位纯数字支付密码！"
      required
      :error-message="payPasswordMessage"
    />
    <van-field
      clearable
      :disabled="otherAccountDisabled"
      v-model="otherAccount"
      type="text"
      label="推荐人账号"
      placeholder="请输入推荐人会员账户（无推荐人可不填）"
    />

    <div class="btnPay" @click="finish()">完成注册</div>
    <div class="care">
      账号规则：长度6-10位 数字、英文组成且必须包含数字及英文
      <br />支付密码：长度6位数字
      <br />密码规则：长度6-14位 数字、英文且必须包含数字及英文
    </div>
    <commonFooter></commonFooter>
  </div>
  <!-- </div> -->
</template>
<script>
import { commonHeader, commonFooter } from "common";
import { passwordReg, phoneReg, userNameReg } from "@/utils/regRex";
import { getMsgCodeApi, regApi } from "@/api/user";
import { getCode, openconfApi } from "@/api";

import { createNamespacedHelpers } from "vuex";
let { mapMutations } = createNamespacedHelpers("user");
import { ACCESS_TOKEN, USER_NAME } from "@/store/mutation-types";
export default {
  name: "recharge",
  components: {
    commonHeader,
    commonFooter
  },
  destroyed() {
    this.smsDisabled = false;
    window.clearInterval(this.smsTimer);
  },
  mounted() {
    this.$toast.loading({
      mask: true,
      message: "加载中..."
    });
    openconfApi({ key: "verify_chan" }).then(res => {
      if (res.code == 200) {
        this.$toast.clear();
        this.msmShow = res.data === "sms" ? true : false;
        if (res.data !== "sms") {
          this.getCode();
        }
      }
    });

    this.otherAccount = this.$route.query.username;
    if (this.otherAccount) {
      this.otherAccountDisabled = true;
    }
  },
  methods: {
    getCode() {
      getCode().then(res => {
        if (res.code == 200) {
          this.codeUrl = res.data.img;
          this.key = res.data.key;
        }
      });
    },
    ...mapMutations(["SET_TOKEN", "SET_NAME"]),
    isSended() {
      if (!this.isSend) {
        this.$refs.sms.blur();
        this.$toast({
          message: "请先获取验证码",
          duration: 500
        });
        return;
      }
      return false;
    },
    clearSms() {
      window.clearInterval(this.smsTimer);
      this.smsMessage = "发送短信验证码";
      this.smsType = "danger";
      this.smsDisabled = false;
    },
    sendSms() {
      this.phoneNumMessage = "";
      if (!this.phoneNum) {
        this.phoneNumMessage = "手机号不能为空";
        return;
      } else if (!phoneReg.test(this.phoneNum)) {
        this.phoneNumMessage = "手机号格式不正确";
        return;
      }
      this.isSend = true;
      let _this = this;
      getMsgCodeApi({
        mobile: _this.phoneNum,
        type: "reg"
      }).then(res => {
        _this.$toast({
          message: res.msg,
          duration: 500,
          onClose: function() {
            if (res.code == 200) {
              let total = 90;
              _this.smsTimer = window.setInterval(() => {
                _this.smsDisabled = true;
                _this.smsMessage = total + "秒之后重发";
                total -= 1;
                if (total < 0) {
                  _this.clearSms();
                }
              }, 1000);
            }
          }
        });
      });
    },
    finish() {
      let _this = this;
      // this.accountMessage = "";
      this.passwordMessage = "";
      this.payPasswordMessage = "";
      // this.phoneNumMessage = "";
      this.smsErrMessage = "";

      // if (!this.account) {
      //   this.accountMessage = "账号不能为空";
      // }

      if (!this.password) {
        this.passwordMessage = "密码不能为空";
      } else if (!passwordReg.test(this.password)) {
        this.passwordMessage = "密码格式格式不正确";
      }

      if (!this.userName) {
        this.userNameMessage = "账号不能为空";
      } else if (!userNameReg.test(this.userName)) {
        this.userNameMessage = "账号格式不正确";
      }

      if (!this.payPassword) {
        this.payPasswordMessage = "支付密码不能为空";
      } else if (!/^\d{6}$/.test(this.payPassword)) {
        this.payPasswordMessage = "支付密码必须由6位数字组成";
      }

      // if (!this.phoneNum) {
      //   this.phoneNumMessage = "手机号不能为空";
      // } else if (!phoneReg.test(this.phoneNum)) {
      //   this.phoneNumMessage = "手机号格式不正确";
      // }

      if (!this.sms) {
        this.smsErrMessage = "验证码不能为空";
      } else if (
        passwordReg.test(this.password) &&
        userNameReg.test(this.userName) &&
        /^\d{6}$/.test(this.payPassword) 
        // && phoneReg.test(this.phoneNum)
      ) {
        let _this = this;
        let postData = {
          password: this.password,
          username: this.userName,
          // mobile: this.phoneNum,
          code: this.sms,
          paypwd: this.payPassword,
          superior: this.otherAccount
        };
        if (!this.smsShow) {
          postData.key = this.key;
        }
        regApi(postData)
          .then(res => {
            _this.$toast({
              message: res.msg,
              duration: 500,
              onClose: function() {
                if (res.code == 200) {
                  _this.$ls.set(
                    ACCESS_TOKEN,
                    res.data.token,
                    7 * 24 * 60 * 60 * 1000
                  );
                  _this.$ls.set(
                    USER_NAME,
                    res.data.userName,
                    7 * 24 * 60 * 60 * 1000
                  );
                  _this.SET_TOKEN(res.data.token);
                  _this.SET_NAME(res.data.username);
                  _this.$router.push("/user");
                  _this.$dispatch("socketConect");
                }
              }
            });
          })
          .catch(err => {
            console.log(err)
          });
      }
    }
  },
  data() {
    return {
      msmShow: false,
      codeUrl: "",
      title: "注册",
      sms: "",
      otherAccountDisabled: false,
      smsTimer: null,
      userName: "",
      userNameMessage: "",
      smsDisabled: "",
      smsErrMessage: "",
      smsMessage: "发送短信验证码",
      smsType: "danger",
      smsDisabled: false,
      account: "",
      password: "",
      payPassword: "",
      otherAccount: "",
      phoneNum: "",
      phoneNumMessage: "",
      accountMessage: "",
      passwordMessage: "",
      isSend: false,
      payPasswordMessage: ""
    };
  }
};
</script>
<style lang="less" scoped>
@import "~styles/variable.less";
.code {
  width: 100px;
  height: 30px;
}
</style>